<template>
  <!-- 顶部渐变背景区域 -->
  <div class="header-section">
    <div class="header-banner">
      <h1 class="banner-title">{{ homeTitle }}</h1>
      <h2 class="banner-subtitle">{{ homeText }}</h2>
    </div>
  </div>

  <!-- 主内容区：白色背景 -->
  <div class="main-content">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      加载中...
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" v-else>
      <div class="card">
        <div class="card-title">总人数</div>
        <div class="card-value" v-text="stats.totalUsers"></div>
        <div class="card-icon">👥</div>
      </div>

      <div class="card">
        <div class="card-title">在线人数</div>
        <div class="card-value online" v-text="stats.onlineUsers"></div>
        <div class="card-icon">🟢</div>
      </div>

      <div class="card">
        <div class="card-title">企业数量</div>
        <div class="card-value" v-text="stats.companyCount"></div>
        <div class="card-icon">🏢</div>
      </div>

      <div class="card">
        <div class="card-title">岗位数量</div>
        <div class="card-value" v-text="stats.jobCount"></div>
        <div class="card-icon">💼</div>
      </div>

      <div class="card">
        <div class="card-title">已投递次数</div>
        <div class="card-value" v-text="stats.deliveredCount"></div>
        <div class="card-icon">📨</div>
      </div>
    </div>

    <!-- ECharts 图表区域：双环形图 -->
    <div class="chart-container" v-if="!loading">
      <div class="charts-wrapper">
        <div ref="ringChartLeft" class="chart"></div>
        <div ref="ringChartRight" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { getHomeNumApi, getHomeTextApi } from '../api/Home';
import * as echarts from 'echarts';

export default {
  name: 'Dashboard',
  data() {
    return {
      stats: {
        totalUsers: 0,
        onlineUsers: 0,
        companyCount: 0,
        jobCount: 0,
        deliveredCount: 0,
      },
      homeTitle: '',
      homeText: '',
      loading: true,
      chartInstance: null
    };
  },
  async mounted() {
    await this.loadHomeData();
    await this.loadHomeText();
    this.initRingCharts();
  },
  methods: {
    async loadHomeData() {
      try {
        const response = await getHomeNumApi();
        const data = response.data;

        this.stats = {
          totalUsers: data.totalUsers || 0,
          onlineUsers: data.onlineUsers || 0,
          companyCount: data.companyCount || 0,
          jobCount: data.jobCount || 0,
          deliveredCount: data.deliveredCount || 0,
        };
      } catch (error) {
        console.error('获取首页统计数据失败：', error);
        this.$message?.error?.('数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    async loadHomeText() {
      try {
        const response = await getHomeTextApi();
        this.homeTitle = response.data.title;
        this.homeText = response.data.text;
      } catch (error) {
      console.error('获取首页文本数据失败：', error);
      }
    },

    initRingCharts() {
      const { totalUsers, onlineUsers, companyCount, jobCount, deliveredCount } = this.stats;
      const offlineUsers = totalUsers - onlineUsers;

      // 左侧环形图实例
      const chartLeft = echarts.init(this.$refs.ringChartLeft);
      // 右侧环形图实例
      const chartRight = echarts.init(this.$refs.ringChartRight);

      // ---------- 左侧环形图：用户活跃情况 ----------
      const optionLeft = {
        title: {
          text: '',
          left: 'center',
          top: '10%',
          textStyle: {
            fontSize: 16,
            color: '#333'
          }
        },
        tooltip: {
          show: false // 关闭默认 tooltip，由中间文字替代
        },
        series: [
          {
            name: '用户分布',
            type: 'pie',
            radius: ['40%', '80%'], // 更粗的环
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10
            },
            label: { show: false }, // 隐藏外部标签
            labelLine: { show: false },
            data: [
              { value: onlineUsers, name: '在线人数', itemStyle: { color: '#4caf50' } },
              { value: offlineUsers, name: '离线人数', itemStyle: { color: '#bdbdbd' } }
            ],
            // 使用 graphic 在中心显示文字
            emphasis: {
              disabled: false
            }
          }
        ],
        // 中间文字（初始状态）
        graphic: {
          elements: [
            {
              type: 'text',
              id: 'centerText',
              style: {
                text: totalUsers > 0 ? `总人数${totalUsers}` : '暂无数据',
                fontSize: 18,
                fontWeight: 'bold',
                lineDash: undefined,
                fill: '#333',
                textAlign: 'center',
                fontFamily: 'Microsoft YaHei'
              },
              left: 'center',
              top: 'middle'
            }
          ]
        }
      };

      // ---------- 右侧环形图：核心数据 ----------
      const optionRight = {
        title: {
          text: '',
          left: 'center',
          top: '10%',
          textStyle: {
            fontSize: 16,
            color: '#333'
          }
        },
        tooltip: {
          show: false
        },
        series: [
          {
            name: '数据统计',
            type: 'pie',
            radius: ['40%', '80%'], // 更粗的环
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10
            },
            label: { show: false },
            labelLine: { show: false },
            data: [
              { value: companyCount, name: '企业数量', itemStyle: { color: '#2196f3' } },
              { value: jobCount, name: '岗位数量', itemStyle: { color: '#ff9800' } },
              { value: deliveredCount, name: '已投递次数', itemStyle: { color: '#9c27b0' } }
            ],
            emphasis: {
              disabled: false
            }
          }
        ],
        graphic: {
          elements: [
            {
              type: 'text',
              id: 'centerText',
              style: {
                text: '',
                fontSize: 18,
                fontWeight: 'bold',
                fill: '#333',
                textAlign: 'center',
                fontFamily: 'Microsoft YaHei'
              },
              left: 'center',
              top: 'middle'
            }
          ]
        }
      };

      // 设置图表
      chartLeft.setOption(optionLeft);
      chartRight.setOption(optionRight);

      // ========== 鼠标悬停事件处理 ==========
      const handleMouseOver = (params, chart, totalText = '') => {
        const name = params.name;
        const value = params.value;
        const seriesName = params.seriesName;

        // 更新中间文字
        chart.setOption({
          graphic: {
            elements: [
              {
                id: 'centerText',
                style: {
                  text: `${name}${value}`
                }
              }
            ]
          }
        });
      };

      const handleMouseOut = (chart, isLeft = false, totalUsers = 0) => {
        let text = '';
        if (isLeft) {
          text = totalUsers > 0 ? `总人数${totalUsers}` : '暂无数据';
        }
        chart.setOption({
          graphic: {
            elements: [
              {
                id: 'centerText',
                style: {
                  text
                }
              }
            ]
          }
        });
      };

      // 左侧图：绑定事件
      chartLeft.on('mouseover', (params) => {
        if (params.data) {
          handleMouseOver(params, chartLeft);
        }
      });
      chartLeft.on('mouseout', () => {
        handleMouseOut(chartLeft, true, totalUsers);
      });

      // 右侧图：绑定事件
      chartRight.on('mouseover', (params) => {
        if (params.data) {
          handleMouseOver(params, chartRight);
        }
      });
      chartRight.on('mouseout', () => {
        handleMouseOut(chartRight);
      });

      // 保存实例
      this.chartInstance = [chartLeft, chartRight];
      window.addEventListener('resize', this.onResize);
    },

    onResize() {
      if (this.chartInstance && Array.isArray(this.chartInstance)) {
        this.chartInstance.forEach(chart => chart?.resize());
      }
    }
  },
  beforeUnmount() {
    if (this.chartInstance && Array.isArray(this.chartInstance)) {
      this.chartInstance.forEach(chart => {
        if (chart) {
          chart.dispose();
        }
      });
    }
    this.chartInstance = null;
    window.removeEventListener('resize', this.onResize);
  }
};
</script>
<style scoped>
/* 顶部渐变区域 */
.header-section {
  width: 100%;
  padding: 40px 20px 30px;
  background: linear-gradient(-45deg, #c6ffdd, #fbd786, #f7797d, #3ad4bd);
  background-size: 400% 400%;
  animation: gradientShift 20s ease infinite;
  position: relative;
  z-index: 10;
  margin-bottom: 0;
  border-bottom-left-radius: 30px;
  border-bottom-right-radius: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.header-banner {
  text-align: center;
  color: white;
}

.banner-title {
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(90deg, #ffffff, #e0f7ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin: 0;
  letter-spacing: 1.2px;
  text-shadow: 0 2px 8px rgba(255, 255, 255, 0.3);
}

.banner-subtitle {
  font-size: 22px;
  font-weight: 600;
  color: #fff;
  margin: 12px 0 0;
  opacity: 0.9;
  text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
}

/* 主内容区 */
.main-content {
  padding: 30px 20px;
  min-height: calc(100vh - 200px);
  background-color: #f5f7fa;
  position: relative;
  z-index: 1;
  border-radius: 20px 20px 0 0;
  margin-top: -20px;
  box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.05);
}

/* 加载状态 */
.loading {
  text-align: center;
  font-size: 18px;
  color: #666;
  margin-top: 60px;
}

/* 统计卡片 */
.stats-cards {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 40px;
  flex-wrap: wrap;
}

.card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  width: 180px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  position: relative;
  text-align: center;
  transition: transform 0.3s, box-shadow 0.3s;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 8px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
}

.card-value.online {
  color: #27ae60;
}

.card-icon {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 20px;
}

/* 图表容器 - 双环形图布局 */
.chart-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin: 0 auto;
  max-width: 1200px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.charts-wrapper {
  display: flex;
  justify-content: space-around;
  gap: 30px;
  width: 100%;
}

.chart {
  flex: 1;
  height: 360px;
  min-width: 300px;
  border-radius: 8px;
}

/* 响应式 */
@media (max-width: 768px) {
  .stats-cards {
    flex-direction: column;
    align-items: center;
  }
  .card {
    width: 240px;
  }
  .charts-wrapper {
    flex-direction: column;
    align-items: center;
  }
  .chart {
    width: 100%;
    height: 300px;
  }
  .banner-title {
    font-size: 24px;
  }
  .banner-subtitle {
    font-size: 20px;
  }
  .main-content {
    padding: 20px 15px;
    margin-top: -10px;
    border-radius: 15px 15px 0 0;
  }
  .header-section {
    padding: 30px 15px 25px;
    border-bottom-left-radius: 20px;
    border-bottom-right-radius: 20px;
  }
}
</style>